﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Micrhard.FMCG.Server.Models;
using Microhard.Permission.Interface;
using Micrhard.FMCG.Server.Interface;
using Microsoft.Practices.Unity;
using Microhard.Permission.MVCFilter;
using System.IO;
using Micrhard.FMCG.Server.Validator;
using FluentValidation;
using System.Text;
using Micrhard.FMCG.Server.Impl;
using Microhard.Core.DBUtility;

namespace Microhard.FMCG.WebUI.Areas.ScanWXCode.Controllers
{
    public class VerifyFakeController : MicroHardBaseController<FakeCodeModel>
    {
        private IVerfFakeCode _resp = null;
        [Dependency]
        public IVerfFakeCode IFcode
        {
            set
            {
                base._repository = value;
                _resp = value;
            }
            get
            {
                return _resp;
            }
        }

        [MVCFilterAtrForLogon(Order = 0)]//登录验证
        [MVCFilterAtrForResourcePermission(OperationKeyName = "Create", Order = 1)]//功能权限验证
        [MVCFilterAtrForCustomeDataPermission(DataScopeactionParameterName = "scope", Order = 2)]//数据权限验证
        public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments, ScopeResult scope)
        {
            //验证导入的数据合法性
            IValidator<FakeCodeModel> wmModelV = new FakeCodeModelValidator();
            StringBuilder sb = new StringBuilder();
            _resp.scope = scope;

            foreach (var file in attachments)
            {
                Stream code = file.InputStream;
                TextReader tr = new StreamReader(code);
                string content = tr.ReadToEnd();
                int totalCount = 0;
                if (content != string.Empty)
                {
                    var items = content.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    totalCount = items.Length;
                    var toAdd = new List<FakeCodeModel>();

                    foreach (var i in items)
                    {
                        var sncode = i.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                        if (sncode.Length == 2)
                        {
                            Guid c = Guid.Empty;
                            if (Guid.TryParse(sncode[1], out c))
                            {
                                var newAdd = new FakeCodeModel
                                {
                                    FakeCodeID = Guid.Empty,
                                    SN = sncode[0],
                                    Code = c
                                };
                                var valresult = wmModelV.Validate(newAdd);
                                if (valresult.IsValid)
                                {
                                    toAdd.Add(newAdd);
                                }
                                else
                                {
                                    foreach (var e in valresult.Errors)
                                    {
                                        sb.AppendLine(e.ErrorMessage);
                                    }
                                }
                            }
                        }
                    }
                    if (sb.Length == 0)
                    {
                        var result = _resp.BatchAdd(toAdd);

                        if (!result.IsSucceed)
                        {
                            return Content(result.ErrorMsgTxt);
                        }
                    }
                    else
                    {
                        return Content(sb.ToString());
                    }
                }

            }
            // Return an empty string to signify success
            return Content("");
        }

        public ActionResult V(string Code)
        {
            if (string.IsNullOrEmpty(Code))
            {
                return View(new FakeCodeModel
                {
                    ErrorMsg = "防伪码为空，无法识别"
                });
            }
            //获取其他信息
            string bt = this.HttpContext.Request.Browser.Type;
            string ip = this.HttpContext.Request.UserHostAddress;
            string n = this.HttpContext.Request.UserHostName;
            //解密code
            var clear = Microhard.Core.Security.EncDec.Decrypt(Code, System.Configuration.ConfigurationManager.AppSettings["FakeCodeKey"]);
            var result = _resp.Verify(new FakeCodeModel
            {
                Code = Guid.Parse(clear),
                Info = bt + "," + ip + "," + n,
                IpAddress = ip
            });
            return View(result);
        }
    }
}
